//
//  UIRTLNavigationController.m
//  iOS-rtl
//
//  Created by Tal Bereznitskey on 8/11/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "UIRTLNavigationController.h"


@implementation UIRTLNavigationController

- (id)initWithRootViewController:(UIViewController *)rootViewController
{
	self = [super initWithRootViewController:rootViewController];
	if (!self)
		return nil;
	return self;
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	NSLog(@"pushViewController");
	// Add the viewController and a fake controller without animation. Then pop the fake controller with animation.
	UIViewController *fakeController = [[[UIViewController alloc] init] autorelease];
	[super setViewControllers:[[self viewControllers] arrayByAddingObjectsFromArray:[NSArray arrayWithObjects:viewController, fakeController, nil]] animated:NO];
	[super popViewControllerAnimated:animated];
}

- (void)popViewControllerAnimatedStep2:(UIViewController *)viewController
{
	// Push the new top controller with animation
	[super pushViewController:viewController animated:YES];
	// Remove the view that should have been popped
	NSMutableArray *arr = [NSMutableArray arrayWithArray:[self viewControllers]];
	[arr removeObjectAtIndex:[[self viewControllers] count]-2];
	[super setViewControllers:[NSArray arrayWithArray:arr] animated:NO];
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
	NSLog(@"popViewControllerAnimated");

	if (animated)
	{
		// Save the controller that should be on top after this pop operation
		UIViewController *newTopController = [[self viewControllers] objectAtIndex:[[self viewControllers] count]-2];
		// Remove it from the stack. Leave the view that should be popped on top
		NSMutableArray *arr = [NSMutableArray arrayWithArray:[self viewControllers]];
		[arr removeObjectAtIndex:[[self viewControllers] count]-2];
		[super setViewControllers:[NSArray arrayWithArray:arr] animated:NO];
		// Schedule the next step
		[self performSelector:@selector(popViewControllerAnimatedStep2:) withObject:newTopController afterDelay:0];
		return [arr objectAtIndex:[arr count]-1];
	}
	return [super popViewControllerAnimated:NO];
}

- (void)dealloc {
    [super dealloc];
}


@end
